package com.kx.center.service.impl.elm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kx.center.entity.Channel;
import com.kx.center.entity.elm.ElmOrder;
import com.kx.center.entity.elm.ElmOrderDetail;
import com.kx.center.mappers.ChannelMapper;
import com.kx.center.mappers.elm.ElmOrderDetailMapper;
import com.kx.center.mappers.elm.ElmOrderMapper;
import com.kx.center.service.elm.ElmOrderService;
import com.kx.center.util.HttpClientUtil;
import com.kx.center.util.JSONParser;
import com.kx.center.util.StringUtil;

@Service
public class ElmOrderServiceImpl implements ElmOrderService {

	@Autowired
	ElmOrderMapper elmOrderMapper;
	@Autowired
	ElmOrderDetailMapper elmOrderDetailMapper;
	@Autowired
	ChannelMapper channelMapper;
	
	@Override
	public void insertElmOrder(ElmOrder elmOrder) {
		elmOrderMapper.insertElmOrder(elmOrder);
	}

	@Override
	public void updateElmOrderStatus(ElmOrder elmOrder) {
		elmOrderMapper.updateElmOrderStatus(elmOrder);
	}

	@Override
	@SuppressWarnings("unchecked")
	public int findElmOrderStatus(Long id) {

		int status = 0;
		
		Channel channel = channelMapper.findKeyById(id);

		try {
			Integer timestamp = null;
			timestamp = (int) (System.currentTimeMillis() / 1000);
			Map<String, String> maps = new HashMap<String, String>();
			maps.put("consumer_key", channel.getAppKey());
			maps.put("timestamp", timestamp.toString());
			String url = "http://v2.openapi.ele.me/order/" + id + "/status/";
			String sig = HttpClientUtil.genSig(url, maps, channel.getAppSecret());
			String params = "&consumer_key="+channel.getAppKey()+"&sig=" + sig
					+ "&timestamp=" + timestamp + "";
			String json = HttpClientUtil.sendGet(url, params);
			HashMap<String, Object> ordermap = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			HashMap<String, Object> list = (HashMap<String, Object>) ordermap
					.get("data");
			status = (int) list.get("status_code");
		} catch (Exception e) {
			System.out.println(e);
		}
		return status;
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public Integer sendConfirmStatusToElm(Long id) {

		Integer code = null;
		Channel channel = channelMapper.findKeyById(id);
		
		try {
			Integer timestamp = null;
			timestamp = (int) (System.currentTimeMillis() / 1000);
			Map<String, String> restaurant = new TreeMap<String, String>();
			restaurant.put("consumer_key", channel.getAppKey());
			restaurant.put("timestamp", timestamp.toString());
			restaurant.put("status", "2");
			String restaurant_url = "http://v2.openapi.ele.me/order/" + id
					+ "/status/";
			String restaurant_sig = HttpClientUtil.genSig(restaurant_url,
					restaurant, channel.getAppSecret());
			String params = "status=2";
			String url = restaurant_url + "?consumer_key="+channel.getAppKey()+"&sig="
					+ restaurant_sig + "&timestamp=" + timestamp + "";
			String json = HttpClientUtil.doPut(url, params);
			HashMap<String, Object> _json = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			code = (Integer) _json.get("code");
		} catch (Exception e) {
			System.out.println(e);
		}
		return code;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Integer sendInvalidStatusToElm(Long id) {

		Integer code = null;
		Channel channel = channelMapper.findKeyById(id);

		try {
			Integer timestamp = null;
			timestamp = (int) (System.currentTimeMillis() / 1000);
			Map<String, String> restaurant = new TreeMap<String, String>();
			restaurant.put("consumer_key", channel.getAppKey());
			restaurant.put("timestamp", timestamp.toString());
			restaurant.put("status", "-1");
			restaurant.put("reason", "超出了配送范围");
			String restaurant_url = "http://v2.openapi.ele.me/order/" + id
					+ "/status/";
			String restaurant_sig = HttpClientUtil.genSig(restaurant_url,
					restaurant, channel.getAppSecret());
			String params = "status=-1&reason=超出了配送范围";
			String url = restaurant_url + "?consumer_key="+channel.getAppKey()+"&sig="
					+ restaurant_sig + "&timestamp=" + timestamp + "";
			String json = HttpClientUtil.doPut(url, params);
			HashMap<String, Object> _json = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			code = (Integer) _json.get("code");
		} catch (Exception e) {
			System.out.println(e);
		}
		return code;
	}

	@Override
	@SuppressWarnings("unchecked")
	public Integer saveElmOrder(String json) {

		Integer elmId = null;

		try {
			HashMap<String, Object> ordermap = (HashMap<String, Object>) JSONParser
					.parse(json, new HashMap<String, Object>().getClass());
			HashMap<String, Object> list = (HashMap<String, Object>) ordermap
					.get("data");
			ElmOrder elmOrder = new ElmOrder();
			elmOrder.setOrderId(list.get("order_id").toString().trim());
			List<String> phonelist = (List<String>) list.get("phone_list");
			for (int i = 0; i < phonelist.size(); i++) {
				String s = phonelist.get(0);
				elmOrder.setPhoneList(s);
			}
			elmOrder.setAddress(list.get("address").toString().trim());
			elmOrder.setCreatedAt(list.get("created_at").toString().trim());
			elmOrder.setDeliverFee(NumberUtils.toDouble(list.get("deliver_fee")
					.toString().trim()));
			elmOrder.setDeliverTime(StringUtil
					.checkString((String) list.get("deliver_time")).toString()
					.trim());
			elmOrder.setDescription(StringUtil
					.checkString((String) list.get("description")).toString()
					.trim());
			elmOrder.setInvoice(StringUtil
					.checkString((String) list.get("invoice")).toString()
					.trim());
			elmOrder.setIsBook(list.get("is_book").toString().trim());
			elmOrder.setIsOnlinePaid(list.get("is_online_paid").toString()
					.trim());
			elmOrder.setRestaurantId(NumberUtils.toInt(list
					.get("restaurant_id").toString().trim()));
			elmId = elmOrder.getRestaurantId();
			elmOrder.setRestaurantName(list.get("restaurant_name").toString()
					.trim());
			elmOrder.setStatusCode(NumberUtils.toInt(list.get("status_code")
					.toString().trim()));
			elmOrder.setUserId(NumberUtils.toInt(list.get("user_id").toString()
					.trim()));
			elmOrder.setUserName(list.get("user_name").toString().trim());
			elmOrder.setTotalPrice(NumberUtils.toDouble(list.get("total_price")
					.toString().trim()));
			elmOrder.setOriginalPrice(NumberUtils.toDouble(list
					.get("original_price").toString().trim()));
			elmOrder.setConsignee(StringUtil
					.checkString((String) list.get("consignee")).toString()
					.trim());
			elmOrder.setDeliveryGeo(list.get("delivery_geo").toString().trim());
			elmOrder.setDeliveryPoiAddress(list.get("delivery_poi_address")
					.toString().trim());
			elmOrderMapper.insertElmOrder(elmOrder);
			ElmOrderDetail elmOrderDetail = new ElmOrderDetail();
			elmOrderDetail.setOrderId(NumberUtils.toLong(list.get("order_id")
					.toString().trim()));
			elmOrderDetail.setRestaurantId(NumberUtils.toInt(list
					.get("restaurant_id").toString().trim()));
			HashMap<String, Object> _detailList = (HashMap<String, Object>) list
					.get("detail");
			ArrayList<HashMap<String, Object>> extraList = (ArrayList<HashMap<String, Object>>) _detailList
					.get("extra");
			for (HashMap<String, Object> extra : extraList) {
				elmOrderDetail.setCategoryId(NumberUtils.toInt(extra
						.get("category_id").toString().trim()));
				elmOrderDetail.setName(extra.get("name").toString().trim());
				elmOrderDetail.setPrice(NumberUtils.toDouble(extra.get("price")
						.toString().trim()));
				elmOrderDetail.setQuantity(NumberUtils.toInt(extra
						.get("quantity").toString().trim()));
				elmOrderDetail.setGarnishId(NumberUtils.toInt(extra.get("id")
						.toString().trim()));
				elmOrderDetail.setSpec(StringUtil
						.checkString((String) list.get("description"))
						.toString().trim());
				elmOrderDetailMapper.insertElmOrderDetail(elmOrderDetail);
			}
			List<ArrayList<HashMap<String, Object>>> detailList = (List<ArrayList<HashMap<String, Object>>>) _detailList
					.get("group");
			for (ArrayList<HashMap<String, Object>> _map : detailList) {
				for (HashMap<String, Object> map : _map) {
					elmOrderDetail.setCategoryId(NumberUtils.toInt(map
							.get("category_id").toString().trim()));
					elmOrderDetail.setName(map.get("name").toString().trim());
					elmOrderDetail.setPrice(NumberUtils.toDouble(map
							.get("price").toString().trim()));
					elmOrderDetail.setQuantity(NumberUtils.toInt(map
							.get("quantity").toString().trim()));
					elmOrderDetail.setGarnishId(NumberUtils.toInt(map.get("id")
							.toString().trim()));
					elmOrderDetailMapper.insertElmOrderDetail(elmOrderDetail);
				}
			}
		} catch (Exception e) {
			System.out.println(e);
		}
		return elmId;
	}

}
